<template>
  <el-dialog :visible="visible" @update:visible="onUpdateVisible" title="修改密码" width="400px" @close="onClose">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="90px">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" type="password" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="onSubmit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '@/utils/axios'

const props = defineProps({
  visible: Boolean
})
const emit = defineEmits(['update:visible'])
const formRef = ref()
const loading = ref(false)
const form = ref({ oldPassword: '', newPassword: '' })
const rules = {
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }]
}

watch(() => props.visible, v => {
  if (v) form.value = { oldPassword: '', newPassword: '' }
})

const onClose = () => emit('update:visible', false)
const onUpdateVisible = v => emit('update:visible', v)
const onSubmit = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    loading.value = true
    try {
      await axios.put('/user/password', form.value)
      ElMessage.success('密码修改成功，请重新登录')
      onClose()
      setTimeout(() => {
        localStorage.removeItem('token')
        window.location.href = '/login'
      }, 1000)
    } catch (e) {}
    loading.value = false
  })
}
</script> 